# coding =utf-8
# @Time :2022/1/23 17:14
# @Author : zcy
# @File : pdf_cut.py
# @SoftWare : PyCharm


import PyPDF2

# 这里狮我们要裁剪的pdf文件名称
f_path = '深入理解Java虚拟机：JVM高级特性与最佳实践（第3版）周志明.pdf'
# 分割后的第一个文件
out_path_1 = 'half_front.pdf'
# 分割后的第二个文件
out_path_2 = 'half_back.pdf'

# 把文件分为两半
with open(f_path, 'rb') as f, open(out_path_1, 'wb') as f_out1, open(out_path_2, 'wb') as f_out2:
    pdf = PyPDF2.PdfFileReader(f)
    pdf_out1 = PyPDF2.PdfFileWriter()
    pdf_out2 = PyPDF2.PdfFileWriter()
    cnt_pages = pdf.getNumPages()
    print(f'共 {cnt_pages} 页')
    center_index = cnt_pages //2
    for i in range(cnt_pages):
        if i <= center_index:
            pdf_out1.addPage(pdf.getPage(i))
        else:
            pdf_out2.addPage(pdf.getPage(i))
    pdf_out1.write(f_out1)
    pdf_out2.write(f_out2)


